/**
 * Class that implements the simulation space of the rabbits grass simulation.
 * @author Liansheng HUA & Yujie GUO
 */

import uchicago.src.sim.space.Object2DGrid; 

public class RabbitsGrassSimulationSpace {

	private Object2DGrid rabbitSpace;
	private Object2DGrid grassSpace;

	public RabbitsGrassSimulationSpace(int xSize, int ySize){

		grassSpace = new Object2DGrid(xSize, ySize);
		rabbitSpace = new Object2DGrid(xSize, ySize);

		for(int i = 0; i < xSize; i++){
			for(int j = 0; j < ySize; j++){
				grassSpace.putObjectAt(i,j,new Integer(0));
			}
		}
	}

	public void growGrass(int grassNum){

		for(int i = 0; i < grassNum; i++){

			int x = (int)(Math.random()*(grassSpace.getSizeX()));
			int y = (int)(Math.random()*(grassSpace.getSizeY()));

			int currentValue = getGrassAt(x, y);

			grassSpace.putObjectAt(x,y,new Integer(currentValue + 1));
		}
	}

	public int getGrassAt(int x, int y){
		int i;
		if(grassSpace.getObjectAt(x,y)!= null){
			i = ((Integer)grassSpace.getObjectAt(x,y)).intValue();
		}
		else{
			i = 0;
		}
		return i;
	}

	public Object2DGrid getCurrentRabbitSpace(){  
		return rabbitSpace;
	}

	public Object2DGrid getCurrentGrassSpace(){  
		return grassSpace;
	}

	public boolean isGridOccupied(int x, int y){
		boolean retVal = false;
		if(rabbitSpace.getObjectAt(x, y)!=null) retVal = true;
		return retVal;
	}

	public boolean addAgent(RabbitsGrassSimulationAgent agent){
		boolean retVal = false;
		int count = 0;
		int countLimit = 10 * rabbitSpace.getSizeX() * rabbitSpace.getSizeY();

		while((retVal==false) && (count < countLimit)){
			int x = (int)(Math.random()*(rabbitSpace.getSizeX()));
			int y = (int)(Math.random()*(rabbitSpace.getSizeY()));
			if(isGridOccupied(x,y) == false){
				rabbitSpace.putObjectAt(x,y,agent);
				agent.setXY(x,y);
				agent.setSpace(this);
				retVal = true;
			}
			count++;
		}

		return retVal;
	}

	public boolean moveAgentAt(int x, int y, int newX, int newY){
		boolean retVal = false;
		if(!isGridOccupied(newX, newY)){
			RabbitsGrassSimulationAgent agent = (RabbitsGrassSimulationAgent)rabbitSpace.getObjectAt(x, y);
			removeAgentAt(x,y);
			agent.setXY(newX, newY);
			rabbitSpace.putObjectAt(newX, newY, agent);
			retVal = true;
		}
		return retVal;
	}

	public void removeAgentAt(int x, int y){
		rabbitSpace.putObjectAt(x, y, null);
	}

	public int eatGrassAt(int x, int y){
		int grassNum = getGrassAt(x, y);
		grassSpace.putObjectAt(x, y, new Integer(0));
		return grassNum;
	}

	public int getTotalGrass(){
		int totalGrass = 0;
		for(int i = 0; i < grassSpace.getSizeX(); i++){
			for(int j = 0; j < grassSpace.getSizeY(); j++){
				totalGrass += getGrassAt(i,j);
			}
		}
		return totalGrass;
	}
}





